import { DatePicker, Form, Input, Modal, Select } from "antd";
import dayjs from "dayjs";
import { useEffect } from "react";
import { apiAddChannel, apiModifyChannel } from "~/api";
import { DictType } from "~/common/enum/dict.enum";
import Title from "~/components/ui/title";
import { useDictsMap } from "~/contexts/dict";
import type { IChannel } from "~/types/manage/channel/list";
import { dictToOption } from "~/utils/ui.util";

interface Props {
  visible: boolean;
  channel?: IChannel | null;
  onCancel?: () => void;
  onOk?: () => void;
}
export default function ChannelModal(props: Props) {
  const [form] = Form.useForm<Partial<IChannel>>();
  const dictsMap = useDictsMap([
    DictType.CONTRACT_TYPE,
    DictType.INVOICE_TYPE,
    DictType.CHANNEL_TYPE,
    DictType.CONTENT_KIND,
    DictType.CONTENT_LENGTH_TYPE,
    DictType.CONTENT_TYPE,
  ]);

  const companyName = Form.useWatch("companyName", form);
  const creditCode = Form.useWatch("creditCode", form);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      const value: IChannel = form.getFieldsValue(true);
      if (
        value.contractTimeRange &&
        value.contractTimeRange?.[0] &&
        value.contractTimeRange?.[1]
      ) {
        value.contractStart = value.contractTimeRange[0].format("YYYY-MM-DD");
        value.contractExpiry = value.contractTimeRange[1].format("YYYY-MM-DD");
      }
      delete value.contractTimeRange;
      if (value.id) {
        await apiModifyChannel(value.id, value);
      } else {
        await apiAddChannel(value);
      }
      props.onOk?.();
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.resetFields();
    if (props.channel) {
      console.log(props.channel);
      form.setFieldsValue({
        ...props.channel,
        contractTimeRange: [
          props.channel.contractStart
            ? dayjs(props.channel.contractStart)
            : null,
          props.channel.contractExpiry
            ? dayjs(props.channel.contractExpiry)
            : null,
        ],
      });
    }
  }, [props.channel, props.visible, form]);

  useEffect(() => {
    form.setFieldValue("invoiceTitle", companyName);
    form.setFieldValue("taxNumber", creditCode);
  }, [companyName, creditCode]);

  return (
    <Modal
      title={props.channel ? "编辑渠道" : "新增渠道"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
      width={800}
    >
      <Form form={form} className="rp-[.ant-form-item]:!mb-0">
        <Title title="渠道基本信息" />
        <div className="my-2 grid grid-cols-2 gap-4 rounded p-4">
          <Form.Item label="渠道名称" name="name" required>
            <Input />
          </Form.Item>
          <Form.Item label="渠道类型" name="type" required>
            <Select options={dictToOption(dictsMap.CHANNEL_TYPE)} />
          </Form.Item>
        </div>
        <Title title="渠道企业信息" />
        <div className="my-2 grid grid-cols-2 gap-4 rounded p-4">
          <Form.Item label="企业名称" name="companyName" required>
            <Input />
          </Form.Item>
          <Form.Item label="社会信用编码" name="creditCode">
            <Input />
          </Form.Item>
        </div>
        <Title title="合同信息" />
        <div className="my-2 grid grid-cols-2 gap-4 rounded p-4">
          <Form.Item label="签署合同类型" name="contractTypeDictCode">
            <Select options={dictToOption(dictsMap.CONTRACT_TYPE)} />
          </Form.Item>
          <Form.Item label="合同起止时间" name="contractTimeRange">
            <DatePicker.RangePicker />
          </Form.Item>
        </div>
        <Title title="开票信息" />
        <div className="my-2 grid grid-cols-3 gap-4 rounded p-4">
          <Form.Item label="发票抬头" name="invoiceTitle">
            <Input disabled />
          </Form.Item>
          <Form.Item label="纳税人识别号" name="taxNumber">
            <Input disabled />
          </Form.Item>
          <Form.Item label="开户银行" name="bankName">
            <Input />
          </Form.Item>
          <Form.Item label="银行账号" name="bankAccount">
            <Input />
          </Form.Item>
          <Form.Item label="公司地址" name="companyAddress">
            <Input />
          </Form.Item>
          <Form.Item label="公司电话" name="companyPhone">
            <Input />
          </Form.Item>
          <Form.Item label="发票类目" name="invoiceCategory">
            <Input />
          </Form.Item>
          <Form.Item label="发票类型" name="invoiceTypeDictCode">
            <Select options={dictToOption(dictsMap.INVOICE_TYPE)} />
          </Form.Item>
          <Form.Item label="发票文件类型" name="invoiceFileType">
            <Input />
          </Form.Item>
          <Form.Item label="税点（%）" name="taxRate">
            <Input />
          </Form.Item>
        </div>
        <Title title="渠道后台信息" />
        <div className="my-2 grid grid-cols-3 gap-4 rounded p-4">
          <Form.Item label="后台地址" name="adminUrl">
            <Input />
          </Form.Item>
          <Form.Item label="账号" name="account">
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password">
            <Input />
          </Form.Item>
        </div>
        <Title title="渠道文章类型" />
        <div className="my-2 grid grid-cols-3 gap-4 rounded p-4">
          <Form.Item label="男女频" name={["channelNovelConfig", "kind"]}>
            <Select
              mode="multiple"
              options={dictToOption(dictsMap.CONTENT_KIND)}
            />
          </Form.Item>
          <Form.Item
            label="文章长度"
            name={["channelNovelConfig", "lengthType"]}
          >
            <Select
              mode="multiple"
              options={dictToOption(dictsMap.CONTENT_LENGTH_TYPE)}
            />
          </Form.Item>
          <Form.Item
            label="文章类型"
            name={["channelNovelConfig", "contentType"]}
          >
            <Select
              mode="multiple"
              options={dictToOption(dictsMap.CONTENT_TYPE)}
            />
          </Form.Item>
        </div>
        <Title title="其他" />
        <div className="my-2 gap-4 rounded p-4">
          <Form.Item label="JSON配置" name="config">
            <Input.TextArea />
          </Form.Item>
        </div>
      </Form>
    </Modal>
  );
}
